
package com.epam.android.training.level1.service;

import com.epam.android.training.level1.R;
import com.epam.android.training.level1.activity.IntentActions;
import com.epam.android.training.level1.activity.SettingsActivity;
import com.epam.android.training.level1.db.dao.PollDao;
import com.epam.android.training.level1.db.dao.impl.PollDaoImpl;
import com.epam.android.training.level1.poll.QuestionBo;
import com.epam.android.training.level1.poll.parser.JsonPollParser;
import com.epam.android.training.level1.poll.parser.PollParser;
import com.epam.android.training.level1.poll.parser.PollParserException;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.format.DateUtils;
import android.util.Log;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author Anton Novikau
 */
public class PollUpdateService extends Service implements IntentActions {
  private static final String TAG = PollUpdateService.class.getSimpleName();

  private Timer job;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String interval = prefs.getString(SettingsActivity.POLL_REFRESH_INTERVAL_KEY, "0");
    job = new Timer("UpdateJob");
    job.schedule(new UpdateJob(), 0, Long.parseLong(interval) * DateUtils.MINUTE_IN_MILLIS);
  }

  @Override
  public void onDestroy() {
    job.cancel();
    super.onDestroy();
  }

  private class UpdateJob extends TimerTask {

    private final PollParser parser = new JsonPollParser();

    private final PollDao pollDao = new PollDaoImpl(PollUpdateService.this);

    @Override
    public void run() {
      InputStream storageSource = getResources().openRawResource(R.raw.poll_storage);
      try {
        Map<String, List<QuestionBo>> storage = parser.parse(storageSource);
        Set<Entry<String, List<QuestionBo>>> storageEntries = storage.entrySet();
        for (Entry<String, List<QuestionBo>> poll : storageEntries) {
          pollDao.createPoll(poll.getKey(), poll.getValue());
        }
        sendBroadcast(new Intent(ACTION_POLL_UPDATED));
        sendBroadcast(new Intent(ACTION_RENEW_WIDGET));
      } catch (PollParserException e) {
        Log.e(TAG, "Unable to parse poll storage", e);
      }
    }
  }
}
